import { http } from "./index";
import { AUTH_TOKEN, USER_KEY } from "../constants";
import { User } from "../types/user";
// const apiUrl = process.env.REACT_APP_BASEURL;

//获取token
export const getToken = () => window.localStorage.getItem(AUTH_TOKEN);
export const getUser = () => {
  let userStr = window.localStorage.getItem(USER_KEY);
  let user: User = userStr ? JSON.parse(userStr) : null;
  return user;
};
//保存token
export const seaveToken = (data: User) => {
  window.localStorage.setItem(AUTH_TOKEN, data.token || "");
  window.localStorage.setItem(USER_KEY, JSON.stringify(data) || "");
  return data;
};

//登录函数
export const login = (data: { name: string; pass: string }) => {
  // return fetch(`${apiUrl}/login`, {
  //   method: "POST",
  //   headers: {
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify(data),
  // }).then(async (res) => {
  //   console.log(res);
  //   if (!res.ok) return Promise.reject(res);
  //   // const data: { user: User } = await res.json();
  //   // const user: User = data.user;
  //   // seaveToken({ user });
  //   // return user;
  //   return seaveToken(await res.json());
  // });
  return http("/users/login", {
    method: "POST",
    data,
  }).then(async (res) => {
    // if (!res.ok) return Promise.reject(res);
    // return seaveToken(await res.json());
    return seaveToken(res);
  });
};

//注册函数
export const register = (data: { name: string; pass: string }) => {
  // return fetch(`${apiUrl}/register`, {
  //   method: "POST",
  //   headers: {
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify(data),
  // }).then(async (res) => {
  //   if (!res.ok) return Promise.reject(res);
  //   return seaveToken(await res.json());
  // });
  return http("/users/register", {
    method: "POST",
    data,
  }).then(async (res) => {
    // if (!res.ok) return Promise.reject(res);
    // return seaveToken(await res.json());
    // return seaveToken(res);
  });
};
//退出登录
export const loginOut = async () => {
  window.localStorage.removeItem(AUTH_TOKEN);
  window.localStorage.removeItem(USER_KEY);
};
